package ninder.system.control;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import ninder.system.model.Paciente;
import ninder.system.util.HibernateUtil;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.SimpleExpression;
import org.hibernate.exception.ConstraintViolationException;



public class PacienteManager {
     
	private static PacienteManager manager = null;

	private PacienteManager() {

	}

	public static synchronized PacienteManager getInstance() {
		if (manager == null) {
			manager = new PacienteManager();
		}
		return manager;
	}

	public Integer createPaciente(Paciente p) {

		return (Integer) HibernateUtil.create(p);
	}

	public void updatePaciente(Paciente p) {

		HibernateUtil.update(p);
	}

	public void deletePaciente(Paciente p) {

		HibernateUtil.delete(p);
	}
	
	
	
	@SuppressWarnings("unchecked")
	public List<Paciente> getAllUsers() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		List<Paciente> result = session.createSQLQuery(
				"select * from paciente order by nome").addEntity("t", Paciente.class).list();
		session.getTransaction().commit();
		return result;
	}
	
	@SuppressWarnings("unchecked")
	public Paciente getPaciente(int id) throws Exception{
		Collection<SimpleExpression> exps = new ArrayList<SimpleExpression>();
		exps.add(Restrictions.like("id", id));
		List<Paciente> paciente = null;
		try {
			paciente = (List<Paciente>) HibernateUtil.createQuery(Paciente.class,
					exps);
		} catch (ConstraintViolationException e) {
			throw new Exception();
		}
	
		return paciente.isEmpty() ? null : paciente.get(0);
	}
}
